<template>
  <div>
    <!--  面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="7">
          <div class="grid-content bg-purple">
          <el-input placeholder="请输入你要搜索的关键字" v-model="queryInfo.query" clearable
          @clear="getUserList">
          <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
          </div>
        </el-col>
        <el-col :span="4"><div class="grid-content bg-purple">
          <el-button type="primary" @click="dialogVisible=true">添加用户</el-button>
        </div></el-col>
      </el-row>
<!--      用户表格-->
      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <!-- stripe: 斑马条纹
        border：边框-->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
<!--    作用域插槽    scope.row得到这一行所有数据
 @change="userStateChanged(scope.row)监听变化 触发函数
-->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              circle
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              circle
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <!--              鼠标是否可进入到 tooltip 中-->
            <el-tooltip
              class="item"
              effect="dark"
              content="角色分配"
              :enterable="false"
              placement="top"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                circle
                @click="showSetRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
<!--    添加用户弹框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%" @close="addDialogClosed">
<!--      添加用户弹框 主体区域 ref="addFormRef"当前表单的引用-->
      <el-form :model="addUser" :rules="addFormRules" ref="addFormRef" label-width="100px" class="demo-ruleForm" >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUser.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input  type="password" v-model="addUser.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUser.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="addUser.mobile"></el-input>
        </el-form-item>
      </el-form>
<!--      底部按钮区域-->
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUserFun">确 定</el-button>
  </span>
    </el-dialog>
<!--    修改用户弹框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editdialogVisible"
      width="50%" @close="editDialogClosed">
      <!-- 主体区域 ref="addFormRef"当前表单的引用-->
      <el-form :model="editUser" :rules="editFormRules" ref="editFormRef" label-width="100px" class="demo-ruleForm" >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editUser.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUser.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="editUser.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!--      底部按钮区域-->
      <span slot="footer" class="dialog-footer">
    <el-button @click="editdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUserFun">确 定</el-button>
  </span>
    </el-dialog>
<!--    修改用户角色弹框-->
    <el-dialog
      title="修改角色"
      :visible.sync="setRoleDialogVisible"
      width="50%" @close="roleDialogClosed">
      <p>当前用户名称：{{this.userInfo.username}}</p>
      <p>当前用户角色：{{this.userInfo.role_name}}</p>
      <p>
        <el-select v-model="seletedRoleId" placeholder="请选择">
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id">
          </el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
    <el-button @click="setRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
  </span>
    </el-dialog>
<!--    分页-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="this.queryInfo.pagenum"
      :page-sizes="[1,2, 5, 10]"
      :page-size="this.queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="this.total">
    </el-pagination>
  </div>

</template>

<script>
export default {
  data() {
    // 自定义邮箱规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        // 合法邮箱
        return callback()
      }
      callback(new Error('请输入合法邮箱'))
    }
    // 自定义手机号规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return callback()
      }
      // 返回一个错误提示
      callback(new Error('请输入合法的手机号码'))
    }
    return {
      // 获取用户列表查询参数对象
      queryInfo: {
        query: '',
        // 当前页数
        pagenum: 1,
        // 每页显示多少数据
        pagesize: 5
      },
      userList: [],
      total: 0,
      dialogVisible: false,
      addUser: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editUser: {},
      editdialogVisible: false,
      // 用户信息
      userInfo: '',
      setRoleDialogVisible: false,
      // 已选中的role id值
      seletedRoleId: '',
      // 角色列表
      roleList: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('用户列表获取失败！')
      }
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 每页显示多少数据 // 监听 pagesize改变的事件
    handleSizeChange (pageSize) {
      // console.log(pageSize)
      this.queryInfo.pagesize = pageSize
      this.getUserList()
    },
    //  当前页数 监听 页码值 改变事件
    handleCurrentChange (currentPage) {
      // console.log(currentPage)
      this.queryInfo.pagenum = currentPage
      this.getUserList()
    },
    // 监听 switch开关 状态改变
    async userStateChanged (userInfo) {
      // console.log(userInfo)
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功！')
    },
    // 监听表单关闭事件，并做重置处理
    addDialogClosed () {
      // alert(11)
      this.$refs.addFormRef.resetFields()
    },
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 添加用户 先进行表单预校验
    addUserFun () {
      this.$refs.addFormRef.validate(async valid => {
        // console.log(valid)
        // 表单预校验失败
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addUser)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败！')
        this.$message.success('添加用户成功！')
        // 隐藏添加用户对话框
        this.dialogVisible = false
        this.getUserList()
      })
    },
    // 修改用户弹框，从数据库中查最新数据
    async showEditDialog (id) {
      const { data: res } = await this.$http.get('users/' + id)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取用户失败！')
      // this.$message.success('获取用户成功！')
      //     // 打开编辑用户对话框
      this.editdialogVisible = true
      this.editUser = res.data
    },
    //  修改用户 先进行表单预校验
    editUserFun () {
      this.$refs.editFormRef.validate(async valid => {
        // console.log(valid)
        // 表单预校验失败
        if (!valid) return
        const { data: res } = await this.$http.put('users/' + this.editUser.id,
          {
            email: this.editUser.email,
            mobile: this.editUser.mobile
          })
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('修改用户失败！')
        this.$message.success('修改用户成功！')
        // 隐藏添加用户对话框
        this.editdialogVisible = false
        this.getUserList()
      })
    },
    async removeUserById (id) {
      // this.$confirm 提示
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 点击确定 返回值为：confirm
      // 点击取消 返回值为： cancel 这个时候要接收错误，并返回出去catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败！')
      this.$message.success('删除用户成功！')
      this.getUserList()
    },
    // 展示分配角色对话框
    async showSetRole (userInfo) {
      this.userInfo = userInfo
      // 去数据库中获取所有角色
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) { return this.$message.error('获取用户角色列表失败！') }
      console.log(res)
      this.roleList = res.data
      this.setRoleDialogVisible = true
    },
    // 保存用户角色信息
    async saveRoleInfo () {
      const { data: res } = await this.$http.put('users/' + this.userInfo.id + '/role', { rid: this.seletedRoleId })
      console.log(res)
      if (res.meta.status !== 200) { return this.$message.error('更新用户角色信息失败！') }
      this.$message.success('更新用户角色成功！')
      this.getUserList()
      this.setRoleDialogVisible = false
    },
    // 监听修改用户角色弹框关闭事件
    roleDialogClosed() {
      this.seletedRoleId = ''
      this.userInfo = ''
    }
  }
}
</script>

<style lang="less" scoped>

</style>
